package _2025_4_13;

import java.util.concurrent.locks.ReentrantLock;

public class TimeoutAvoidExample {
    private static final ReentrantLock lock1 = new ReentrantLock();
    private static final ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> {
            try {
                if (lock1.tryLock()) { // 尝试获取 lock1
                    System.out.println("线程 A: 持有 lock1");
                    Thread.sleep(100);
                    if (lock2.tryLock()) { // 尝试获取 lock2
                        System.out.println("线程 A: 持有 lock2");
                        lock2.unlock(); // 释放 lock2
                    } else {
                        System.out.println("线程 A: 无法获取 lock2，放弃");
                    }
                    lock1.unlock(); // 释放 lock1
                } else {
                    System.out.println("线程 A: 无法获取 lock1，放弃");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                if (lock2.tryLock()) {
                    System.out.println("线程 B: 持有 lock2");
                    Thread.sleep(100);
                    if (lock1.tryLock()) {
                        System.out.println("线程 B: 持有 lock1");
                        lock1.unlock();
                    } else {
                        System.out.println("线程 B: 无法获取 lock1，放弃");
                    }
                    lock2.unlock();
                } else {
                    System.out.println("线程 B: 无法获取 lock2，放弃");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadA.start();
        threadB.start();
    }
}